<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { getUserStatistics, getCourseStatistics, getArticleStatistics } from '@/api/course'

// 图表实例
const userChart = ref(null)
const articleChart = ref(null)

// 统计数据
const userStats = ref({ studentCount: 0, teacherCount: 0, dailyNewUsers: [] })
const courseStats = ref({ totalCount: 0 })
const articleStats = ref({ totalCount: 0, dailyNewArticles: [] })

// 加载数据
const loadData = async () => {
  try {
    const [userRes, courseRes, articleRes] = await Promise.all([
      getUserStatistics(),
      getCourseStatistics(),
      getArticleStatistics()
    ])
    if ((userRes.code === 0 || userRes.code === 200) && userRes.data) {
      userStats.value = userRes.data
    }
    if ((courseRes.code === 0 || courseRes.code === 200) && courseRes.data) {
      courseStats.value = courseRes.data
    }
    if ((articleRes.code === 0 || articleRes.code === 200) && articleRes.data) {
      articleStats.value = articleRes.data
    }
    initUserChart()
    initArticleChart()
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败，请稍后重试')
  }
}

// 用户新增趋势图
const initUserChart = () => {
  if (!userChart.value) return
  const chart = echarts.init(userChart.value)
  const days = userStats.value.dailyNewUsers?.map(item => item.date) || []
  const values = userStats.value.dailyNewUsers?.map(item => item.count) || []
  const option = {
    title: { text: '最近7天新增用户', left: 'center' },
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', data: days },
    yAxis: { type: 'value' },
    series: [{ data: values, type: 'line', smooth: true }]
  }
  chart.setOption(option)
}

// 文章新增趋势图
const initArticleChart = () => {
  if (!articleChart.value) return
  const chart = echarts.init(articleChart.value)
  const days = articleStats.value.dailyNewArticles?.map(item => item.date) || []
  const values = articleStats.value.dailyNewArticles?.map(item => item.count) || []
  const option = {
    title: { text: '最近7天新增文章', left: 'center' },
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', data: days },
    yAxis: { type: 'value' },
    series: [{ data: values, type: 'line', smooth: true }]
  }
  chart.setOption(option)
}

const handleResize = () => {
  echarts.getInstanceByDom(userChart.value)?.resize()
  echarts.getInstanceByDom(articleChart.value)?.resize()
}

onMounted(() => {
  loadData()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<template>
  <div class="analytics-container">
    <!-- 数据概览 -->
    <el-row :gutter="20" class="data-overview">
      <el-col :span="6">
        <el-card class="overview-card">
          <template #header>
            <div class="card-header"><span>学生总数</span></div>
          </template>
          <div class="overview-value">{{ userStats.studentCount }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="overview-card">
          <template #header>
            <div class="card-header"><span>教师总数</span></div>
          </template>
          <div class="overview-value">{{ userStats.teacherCount }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="overview-card">
          <template #header>
            <div class="card-header"><span>课程总数</span></div>
          </template>
          <div class="overview-value">{{ courseStats.totalCount }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="overview-card">
          <template #header>
            <div class="card-header"><span>文章总数</span></div>
          </template>
          <div class="overview-value">{{ articleStats.totalCount }}</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 折线图 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <div ref="userChart" class="chart"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <div ref="articleChart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
.analytics-container {
  padding: 20px;
}
.data-overview {
  margin-bottom: 20px;
}
.overview-card {
  text-align: center;
}
.overview-value {
  font-size: 36px;
  font-weight: bold;
  color: #409EFF;
  margin: 20px 0;
}
.charts-row {
  margin-bottom: 20px;
}
.chart-card {
  margin-bottom: 20px;
}
.chart {
  height: 400px;
  width: 100%;
}
:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #EBEEF5;
  box-sizing: border-box;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 